<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Models\AgentUser;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Mews\Captcha\Facades\Captcha;
use Tymon\JWTAuth\JWTGuard;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class AuthController extends Controller
{
    /**
     * @var JWTGuard
     */
    private $auth;

    /**
     * AuthController constructor.
     */
    public function __construct()
    {
        $this->auth = Auth::guard('agent-admin');
    }

    /** 管理后台入口  */
    public function home()
    {
        $title = '版版通商城代理商后台';

        return view('agent-admin', [
            'title' => $title,
            'view_path' => './lay-agent-admin/',
            'debug' => config('app.debug') ? 1 : 0,
            'static_version' => time(), // 不缓存表态资源
        ]);
    }

    /** 获取图片验证码 */
    public function captcha()
    {
        return Captcha::create('math', true);
    }

    /** 用户名密码登录（加验证码） */
    public function passwordLoginWithCaptcha()
    {
        $param = request()->validate([
            'captcha' => 'required',
            'key' => 'required',
            'username' => 'required',
            'password' => 'required',
        ]);
        if (!captcha_api_check(request()->captcha, request()->key, 'math')) {
            throw new AdminException('验证码错误');
        }
        $user = AgentUser::findByName($param['username']);
        if ($user && Hash::check($param['password'], $user->password)) {
            $token = $this->auth->login($user);

            return ['access_token' => $token];
        }

        throw new AdminException('用户名或密码错误');
    }

    /** 查询个人信息 */
    public function profile()
    {
        /* @var AgentUser $user */
        return $this->auth->user();
    }

    /** 更新个人信息 */
    public function updateProfile()
    {
        $param = request()->validate([
            'real_name' => 'nullable',
            'mobile' => 'nullable',
            'email' => 'nullable',
        ]);

        /** @var AgentUser $user */
        $user = $this->auth->user();
        $user->real_name = $param['real_name'] ?? '';
        $user->mobile = $param['mobile'] ?? '';
        $user->email = $param['email'] ?? '';
        $user->save();
    }

    /** 修改密码 */
    public function changePassword()
    {
        $param = request()->validate([
            'old_password' => 'required',
            'new_password' => 'required',
        ]);

        /** @var AgentUser $user */
        $user = Auth::user();
        if (!Hash::check($param['old_password'], $user->password)) {
            throw new AdminException('当前密码错误');
        }
        $user->password = Hash::make($param['new_password']);
        $user->save();
    }

    public function qrcodeInit()
    {
        $user = Auth::user();

        $url = 'https://vue.banquan520.cn/#/home?agent_id=' . $user->agent_id;

        $qrCode = QrCode::create($url)//跳转地址
            ->setEncoding(new Encoding('UTF-8'))
            ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
            ->setSize(150)//大小
            ->setMargin(20)//边距
            ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->setForegroundColor(new Color(0, 0, 0))
            ->setBackgroundColor(new Color(255, 255, 255));

        $writer = new PngWriter();

        $result = $writer->write($qrCode);

        $dataUri = $result->getDataUri();

        $user->qrcode = $dataUri;

        $user->save();

        return ['qrcode' => $dataUri];
    }
}
